import { SaveOutlined } from '@ant-design/icons';
import {
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { Col, Divider, Form, Row } from 'antd';
import { forwardRef, useImperativeHandle } from 'react';
import EditableTable from '../EditableTable';
import type { FormFieldConfig } from '../types';
import { t } from '../utils/index';
import './index.less';

export interface FormSection {
  title: string;
  fields: FormFieldConfig[];
}

export interface CommonFormProps {
  fields?: FormFieldConfig[]; // 兼容旧的使用方式
  sections?: FormSection[]; // 新的分组方式
  initialValues?: Record<string, any>;
  form?: FormInstance;
  onValuesChange?: (changedValues: any, allValues: any) => void;
  className?: string;
  gutter?: number;
  disabled?: boolean;
  defaultSectionTitle?: string; // 默认分组标题
}

export interface CommonFormRef {
  form: FormInstance;
  validateFields: () => Promise<any>;
  resetFields: () => void;
  setFieldsValue: (values: Record<string, any>) => void;
  getFieldsValue: () => Record<string, any>;
}

const CommonForm = forwardRef<CommonFormRef, CommonFormProps>(
  (
    {
      fields,
      sections,
      initialValues,
      form: externalForm,
      onValuesChange,
      className,
      gutter = 16,
      disabled = false,
      defaultSectionTitle = 'baseInfo',
    },
    ref,
  ) => {
    const [form] = Form.useForm();
    const currentForm = externalForm || form;

    // 处理兼容性：如果只传了 fields，则转换为 sections 格式
    const formSections: FormSection[] =
      sections || (fields ? [{ title: t('common', defaultSectionTitle), fields }] : []);

    useImperativeHandle(ref, () => ({
      form: currentForm,
      validateFields: () => currentForm.validateFields(),
      resetFields: () => currentForm.resetFields(),
      setFieldsValue: (values: Record<string, any>) => currentForm.setFieldsValue(values),
      getFieldsValue: () => currentForm.getFieldsValue(),
    }));

    // 使用 Form.Item dependencies 来监听字段变化，实现动态字段控制
    const renderField = (field: FormFieldConfig, formValues: Record<string, any> = {}) => {
      // 判断字段是否可见
      let isVisible = true;
      if (field?.visible !== undefined) {
        if (typeof field.visible === 'boolean') {
          isVisible = field.visible;
        } else if (typeof field.visible === 'function') {
          isVisible = field.visible(formValues);
        }
      }

      // 如果字段不可见，返回 null
      if (!isVisible) return null;

      // 处理动态选项
      let dynamicOptions = field.options;
      if (field.dynamicOptions && typeof field.dynamicOptions === 'function') {
        dynamicOptions = field.dynamicOptions(formValues);
      }

      const commonProps: FormFieldConfig['props'] = {
        name: field.name,
        label: field.label,
        rules: field.rules,
        placeholder: field.placeholder,
        dependencies: field.dependencies, // 添加依赖字段监听
        ...field.props,
      };

      const colProps = {
        span: field.span || 12,
      };

      const fieldElement = (() => {
        switch (field.type) {
          case 'input':
            return (
              <ProFormText
                {...commonProps}
                allowClear
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...field.fieldProps,
                }}
              />
            );

          case 'select':
            return (
              <ProFormSelect
                {...commonProps}
                options={dynamicOptions} // 使用动态选项
                allowClear
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...field.fieldProps,
                }}
              />
            );

          case 'dateRange':
            return (
              <ProFormDateRangePicker
                {...commonProps}
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );

          case 'date':
            return (
              <ProFormDatePicker
                {...commonProps}
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );

          case 'number':
            return (
              <ProFormDigit
                {...commonProps}
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );

          case 'textarea':
            return (
              <ProFormTextArea
                {...commonProps}
                fieldProps={{
                  rows: 4,
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );

          case 'upload':
            return (
              <ProFormUploadButton
                {...commonProps}
                icon={<SaveOutlined />}
                max={1}
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );

          case 'switch':
            return <ProFormSwitch {...commonProps} />;

          case 'editTable':
            return (
              <Form.Item {...commonProps} style={{ marginBottom: '20px' }}>
                <EditableTable config={field.editTableConfig} disabled={disabled} />
              </Form.Item>
            );

          default:
            return (
              <ProFormText
                {...commonProps}
                allowClear
                fieldProps={{
                  style: { borderRadius: '8px' },
                  ...commonProps.fieldProps,
                }}
              />
            );
        }
      })();

      return (
        <Col key={field.name} {...colProps}>
          {fieldElement}
        </Col>
      );
    };

    // 获取所有字段的依赖项
    const allDependencies = formSections
      .flatMap((section) => section.fields)
      .flatMap((f) => f.dependencies || [])
      .filter(Boolean);

    return (
      <div className={className}>
        <Form
          form={currentForm}
          layout="vertical"
          initialValues={initialValues}
          onValuesChange={onValuesChange}
          scrollToFirstError
          disabled={disabled}
          style={
            {
              '--ant-form-item-margin-bottom': '20px',
            } as React.CSSProperties
          }
        >
          <Form.Item dependencies={allDependencies} noStyle>
            {({ getFieldsValue }) => {
              const formValues = getFieldsValue();
              return (
                <>
                  {formSections.map((section, sectionIndex) => (
                    <div key={`section-${sectionIndex}`}>
                      <Divider orientation="left" style={{ borderColor: 'var(--theme-primary)' }}>
                        {section.title}
                      </Divider>
                      <Row gutter={gutter}>{section.fields.map((field) => renderField(field, formValues))}</Row>
                    </div>
                  ))}
                </>
              );
            }}
          </Form.Item>
        </Form>
      </div>
    );
  },
);

CommonForm.displayName = 'CommonForm';

export default CommonForm;
